home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_07 / pugh / bcdasc.c < prev   
Encoding:
C/C++ Source or Header  |  1994-05-02  |  1.5 KB  |  46 lines

  1. #include <stdio.h>
  2.     enum round_type {ROUND_UP, TRUNCATE, /** other types **/};
  3.  
  4. void round_double(double value, 
  5.     enum round_type round_type, int position,
  6.     char output[])
  7.     {
  8.     double out_value;
  9.             static double round_offset[] =
  10.                     {.5, .05, .005, .0005 /* ... */ };
  11.             static char format[][10] =
  12.                     {"%.0lf", "%.1lf", "%.2lf", "%.3lf"/* ... */};
  13.             switch(round_type)
  14.                     {
  15.             case ROUND_UP:
  16.                     /* No change, since printf does rounding */
  17.                     out_value = value;
  18.                     break;
  19.             case TRUNCATE:
  20.                     out_value = value - round_offset[position];
  21.                     break;
  22.             /** Any other types of alternatives */
  23.                     }
  24.             sprintf(output, format[position], out_value);
  25.             return;
  26.     }
  27.  
  28. void main()
  29.     {
  30.     double d = 341.456;
  31.     char out[50];
  32.     round_double(d, ROUND_UP, 0, out);
  33.     printf("Output for 0 up %s\n",out);
  34.     round_double(d, ROUND_UP, 1, out);
  35.     printf("Output for 1 up %s\n",out);
  36.     round_double(d, ROUND_UP, 2, out);
  37.     printf("Output for 2 up %s\n",out);
  38.     round_double(d, TRUNCATE, 0, out);
  39.     printf("Output for 0 truncate %s\n",out);
  40.     round_double(d, TRUNCATE, 1, out);
  41.     printf("Output for 1 truncate %s\n",out);
  42.     round_double(d, TRUNCATE, 2, out);
  43.  
  44.     printf("Output for 2 truncate %s\n",out);
  45.     }
  46.